package com.lizicloud.infrastructure.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

/**
 * 数据库初始化器
 * 用于检查和修复数据库表结构
 */
@Slf4j
@Component
public class DatabaseInitializer implements CommandLineRunner {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Override
    public void run(String... args) throws Exception {
        try {
            // 检查users表是否存在is_delete字段
            String checkColumnSql = "SELECT COUNT(*) FROM information_schema.COLUMNS " +
                                   "WHERE TABLE_SCHEMA = 'lizi_cloud' " +
                                   "AND TABLE_NAME = 'users' " +
                                   "AND COLUMN_NAME = 'is_delete'";
            
            Integer columnCount = jdbcTemplate.queryForObject(checkColumnSql, Integer.class);
            
            if (columnCount == null || columnCount == 0) {
                log.info("检测到users表缺少is_delete字段，正在添加...");
                
                // 添加is_delete字段
                String addColumnSql = "ALTER TABLE users ADD COLUMN is_delete INT DEFAULT 0 COMMENT '逻辑删除：0-未删除，1-已删除'";
                jdbcTemplate.execute(addColumnSql);
                
                log.info("成功添加is_delete字段到users表");
            } else {
                log.info("users表已存在is_delete字段");
            }
            
        } catch (Exception e) {
            log.error("数据库初始化失败: {}", e.getMessage(), e);
        }
    }
}